import React, { useState } from 'react';
import { InboxOutlined } from '@ant-design/icons';
import { Button, Card, message, Space, Spin } from 'antd';
import type { GetProp, UploadFile, UploadProps } from 'antd';
import { BACKEND_HOST_LOCAL, BACKEND_HOST_PROD } from '@/constants';
import Dragger from 'antd/es/upload/Dragger';
import {
  createClassificationFromExcelUsingPost,
  createDtuFromExcelUsingPost,
} from '@/services/backend/excelController';

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
const contentStyle: React.CSSProperties = {
  padding: 50,
  background: 'rgba(0, 0, 0, 0.05)',
  borderRadius: 4,
};

const content = <div style={contentStyle} />;
const ClassificationPage: React.FC = () => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [uploading, setUploading] = useState(false);
  const url = `${BACKEND_HOST_PROD}/downloadlog/classification.xls`;
  const handleUpload = async () => {
    const formData = new FormData();
    fileList.forEach((file) => {
      formData.append('file', file as FileType);
    });
    setUploading(true);
    await createClassificationFromExcelUsingPost({
      file: formData.get('file'),
    })
      .then((res) => {
        if (res.code === 0) {
          setFileList([]);
          message.success('能耗分类 导入成功');
        } else {
          message.error(res.message);
        }
      })
      .catch((res) => {
        message.error(res.message);
      })
      .finally(() => {
        setUploading(false);
      });
  };

  const props: UploadProps = {
    onRemove: (file) => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    maxCount: 1,
    accept: '.xlsx,.xls',
    beforeUpload: (file) => {
      setFileList([...fileList, file]);

      return false;
    },
    fileList,
  };

  return (
    <>
      <Space direction="vertical" size={16}>
        <Card
          title="能耗分类导入"
          style={{ width: 800 }}
          extra={<a href={url}>能耗分类模版文件下载</a>}
        >
          <Dragger {...props}>
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">点击或者拖拽上传文件</p>
          </Dragger>
          <Button
            type="primary"
            onClick={handleUpload}
            disabled={fileList.length === 0}
            loading={uploading}
            style={{ marginTop: 16 }}
          >
            {uploading ? '上传中' : '上传文件'}
          </Button>
        </Card>
        <Spin fullscreen={true} spinning={uploading} tip="Loading">
          {content}
        </Spin>
      </Space>
    </>
  );
};

export default ClassificationPage;
